package com.xbts.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.core.domain.entity.SysUser;
import com.xbts.common.enums.EmailTypeEnum;
import com.xbts.common.enums.ShoppingCarEnums;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.SnowFlakeUtil;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.SysMessage;
import com.xbts.system.domain.dto.EmailSendDTO;
import com.xbts.system.mapper.SysUserMapper;
import com.xbts.system.module.payment.enums.PaymentMethodEnum;
import com.xbts.system.module.payment.service.ICnWalletLogService;
import com.xbts.system.service.ISysMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbts.system.mapper.CnRechargeToCorporateAccountLogMapper;
import com.xbts.system.domain.CnRechargeToCorporateAccountLog;
import com.xbts.system.service.ICnRechargeToCorporateAccountLogService;
import com.xbts.common.utils.DateUtils;
import com.xbts.common.utils.SecurityUtils;

/**
 * 对公账户充值记录Service业务层处理
 * 
 * @author xbts
 * @date 2023-11-29
 */
@Service
public class CnRechargeToCorporateAccountLogServiceImpl  extends ServiceImpl<CnRechargeToCorporateAccountLogMapper, CnRechargeToCorporateAccountLog> implements ICnRechargeToCorporateAccountLogService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysMessageService sysMessageService;
    @Autowired
    private ICnWalletLogService cnWalletLogService;

    @Autowired
    private EmailSendService emailSendService;

    /**
     * 查询对公账户充值记录列表
     *
     * @param cnRechargeToCorporateAccountLog 对公账户充值记录
     * @return 对公账户充值记录
     */
    @Override
    public List<CnRechargeToCorporateAccountLog> selectCnRechargeToCorporateAccountLogList(CnRechargeToCorporateAccountLog cnRechargeToCorporateAccountLog) {
        QueryWrapper<CnRechargeToCorporateAccountLog> queryWrapper = cnRechargeToCorporateAccountLog.queryWrapper();
        return list(queryWrapper);
    }

    /**
     * 查询对公账户充值记录
     *
     * @param id 对公账户充值记录主键
     * @return 对公账户充值记录
     */
    @Override
    public CnRechargeToCorporateAccountLog selectCnRechargeToCorporateAccountLogById(String id) {
        return getById(id);
    }

    /**
     * 新增对公账户充值记录
     *
     * @param cnRechargeToCorporateAccountLog 对公账户充值记录
     * @return 结果
     */
    @Override
    public boolean insertCnRechargeToCorporateAccountLog(CnRechargeToCorporateAccountLog cnRechargeToCorporateAccountLog) {
        BigDecimal amount = cnRechargeToCorporateAccountLog.getAmount();
        if(amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("充值金额需大于0");
        }
        String id = String.valueOf(SnowFlakeUtil.getSnowFlakeId());
        cnRechargeToCorporateAccountLog.setId(id);
        if(SecurityUtils.isManager()) {
            String userId = cnRechargeToCorporateAccountLog.getUserId();
            SysUser user = userMapper.selectUserById(Long.valueOf(userId));
            cnRechargeToCorporateAccountLog.setNickName(user.getNickName());
            cnRechargeToCorporateAccountLog.setStatus("2");
            // 增加用户余额
            cnWalletLogService.updateUserBalanceAndLog(Long.parseLong(cnRechargeToCorporateAccountLog.getUserId()),
                    cnRechargeToCorporateAccountLog.getAmount(),
                    PaymentMethodEnum.ACCOUNT.name(), null, ShoppingCarEnums.RECHARGE, cnRechargeToCorporateAccountLog.getId(), null);
        } else {

            cnRechargeToCorporateAccountLog.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
            cnRechargeToCorporateAccountLog.setStatus("1");
            cnRechargeToCorporateAccountLog.setUserId(SecurityUtils.getUserId().toString());
            // 判断用户是否存在两条以上的未审核记录
            long count = count(new LambdaQueryWrapper<CnRechargeToCorporateAccountLog>()
                    .eq(CnRechargeToCorporateAccountLog::getUserId, cnRechargeToCorporateAccountLog.getUserId())
                    .eq(CnRechargeToCorporateAccountLog::getStatus, "1"));
            if(count > 1) {
                throw new ServiceException("您有两条以上的未审核的充值记录，请耐心等待");
            }
        }
        cnRechargeToCorporateAccountLog.setCreateBy(SecurityUtils.getUserId().toString());
        return save(cnRechargeToCorporateAccountLog);
    }

    /**
     * 修改对公账户充值记录
     *
     * @param cnRechargeToCorporateAccountLog 对公账户充值记录
     * @return 结果
     */
    @Override
    public boolean updateCnRechargeToCorporateAccountLog(CnRechargeToCorporateAccountLog cnRechargeToCorporateAccountLog) {

        CnRechargeToCorporateAccountLog dblog = getById(cnRechargeToCorporateAccountLog.getId());
        if(!dblog.getStatus().equals("1")){
            throw new ServiceException("该充值记录已审核，请勿重复操作!");
        }
        String title = "对公账户充值审核结果通知";
        String content = "您于：" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dblog.getCreateTime()) + "发起的对公账户充值审核，金额为：" + dblog.getAmount() + "。";
        // 发送消息
        SysMessage message = new SysMessage();
        List<Long> longs = new ArrayList<>();
        message.setUserIds(longs);
        message.setNoticeType(2);
        longs.add(Long.valueOf(dblog.getUserId()));

        String status = cnRechargeToCorporateAccountLog.getStatus();

        String reviewStatus = "成功";
        if(status.equals("2")) {
            reviewStatus = "成功";
            dblog.setReviewer(SecurityUtils.getLoginUser().getUser().getNickName());
            content += "审核通过！已将金额充值到您的余额。";

            // 增加用户余额
            cnWalletLogService.updateUserBalanceAndLog(Long.parseLong(dblog.getUserId()),
                    dblog.getAmount(),
                    PaymentMethodEnum.ACCOUNT.name(), null, ShoppingCarEnums.RECHARGE, dblog.getId(), null);

        } else if(status.equals("3")) {
            reviewStatus = "失败";
            if(StringUtils.isBlank(cnRechargeToCorporateAccountLog.getRemark())){
                throw new ServiceException("审核意见不能为空！");
            }
            cnRechargeToCorporateAccountLog.setReviewer(SecurityUtils.getLoginUser().getUser().getNickName());
            content += "审核未通过！未通过的原因为：" + cnRechargeToCorporateAccountLog.getRemark();
        } else {
            throw new ServiceException("审核状态不合法！");
        }
        cnRechargeToCorporateAccountLog.setUpdateBy(SecurityUtils.getUserId().toString());
        cnRechargeToCorporateAccountLog.setUpdateTime(DateUtils.getNowDate());
        cnRechargeToCorporateAccountLog.setReviewer(SecurityUtils.getLoginUser().getUser().getNickName());
        message.setNoticeTitle(title);
        message.setNoticeContent(content);

        message.setIsAll(1);
        sysMessageService.addSysMessage(message);

        // 发送邮件
        //获取用户邮箱地址
        String email = userMapper.getEmailByUserId(SecurityUtils.getUserId());
        emailSendService.sendMessage(new EmailSendDTO(email, title, EmailTypeEnum.RECHARGE,
                DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dblog.getCreateTime()),
                dblog.getAmount().toString(), reviewStatus
                ));

        return updateById(cnRechargeToCorporateAccountLog);
    }

    /**
     * 批量删除对公账户充值记录
     *
     * @param ids 需要删除的对公账户充值记录主键
     * @return 结果
     */
    @Override
    public boolean deleteCnRechargeToCorporateAccountLogByIds(List<String> ids) {
        return removeBatchByIds(ids);
    }

    /**
     * 删除对公账户充值记录信息
     *
     * @param id 对公账户充值记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean deleteCnRechargeToCorporateAccountLogById(String id) {
      return removeById(id);
    }

}
